package org.dtrd.modules.patient.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.DateUnit;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.dynamic.datasource.annotation.DS;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.dtrd.config.system.Constant;
import org.dtrd.modules.doctor.entity.po.DtrdRlDoctorPatient;
import org.dtrd.modules.doctor.service.IDtrdRlDoctorPatientService;
import org.dtrd.modules.patient.entity.po.DtrdEntRdPatient;
import org.dtrd.modules.patient.entity.po.DtrdRlGroupPatient;
import org.dtrd.modules.patient.mapper.DtrdRlGroupPatientMapper;
import org.dtrd.modules.patient.service.IDtrdEntRdPatientService;
import org.dtrd.modules.patient.service.IDtrdRlGroupPatientService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.Objects;
import java.util.Set;

/**
 * <p>
 * 分组-患者 服务实现类
 * </p>
 *
 * @author QR
 * @since 2021-10-03
 */
@Service
@DS("multi-datasource1")
public class DtrdRlGroupPatientServiceImpl extends ServiceImpl<DtrdRlGroupPatientMapper, DtrdRlGroupPatient> implements IDtrdRlGroupPatientService {

    @Autowired
    private IDtrdEntRdPatientService patientService;
    @Autowired
    private IDtrdRlDoctorPatientService doctorPatientRlService;

    @Transactional
    @Override
    public boolean batchGroupPatients(Integer groupId, Set<Integer> patientIds) {

        DtrdRlGroupPatient groupPatient;
        for (Integer patientId : patientIds) {
            // 校验传入的 patientId 是否有记录, 没有则返回失败
            DtrdEntRdPatient queryPatient = patientService.getById(patientId);
            if (queryPatient == null) {
                return false;
            }
            groupPatient = selectOneByCondition(patientId);
            // 已经有分组记录的 patient 更新 groupId 字段, 否则新增 groupPatient 数据
            // 如果传入的 groupId 和 已经存在的关系记录的 groupId 相同就不做处理
            if (groupPatient != null && !Objects.equals(groupPatient.getGroupId(), groupId)) {
                groupPatient.setGroupId(groupId);
                // 更新分组也设置一次 createTime, createTime记录
                groupPatient.setCreateTime(new Date());
                baseMapper.updateById(groupPatient);
            } else if (groupPatient == null){
                DtrdRlGroupPatient newGroupPatient = new DtrdRlGroupPatient().init();
                newGroupPatient.setGroupId(groupId);
                newGroupPatient.setPatientId(patientId);
                baseMapper.insert(newGroupPatient);
            }
            // 更新医患关系表的数据
            LambdaQueryWrapper<DtrdRlDoctorPatient> wrapper = Wrappers.lambdaQuery(DtrdRlDoctorPatient.class)
                    .eq(DtrdRlDoctorPatient::getPatientId, patientId)
                    .last("limit 1");
            DtrdRlDoctorPatient doctorPatient = doctorPatientRlService.getOne(wrapper);
            if (doctorPatient != null) {
                doctorPatient.setGroupId(groupId);
                doctorPatientRlService.updateById(doctorPatient);
            }
        }
        return true;
    }

    @Override
    public String getPatientInManageDay(Integer patientId) {
        DtrdRlGroupPatient groupPatient = getOne(Wrappers.lambdaQuery(DtrdRlGroupPatient.class)
                .eq(DtrdRlGroupPatient::getPatientId, patientId));
        if (groupPatient != null && (groupPatient.getGroupId().equals(Constant.Group.IN_MANAGE.getType())
                || groupPatient.getGroupId().equals(Constant.Group.CONTINUE_MANAGE.getType()))) {
            Date createTime = groupPatient.getCreateTime();
            long week = DateUtil.between(createTime, new Date(), DateUnit.WEEK);
            return (int) week + Constant.PeriodUnit.WEEK.getName();
        }
        return null;
    }

    private DtrdRlGroupPatient selectOneByCondition(Integer patientId){
        LambdaQueryWrapper<DtrdRlGroupPatient> lambdaQueryWrapper = Wrappers.lambdaQuery(DtrdRlGroupPatient.class)
                .eq(DtrdRlGroupPatient::getIsDel, 0);
        if (patientId != null) {
            lambdaQueryWrapper.eq(DtrdRlGroupPatient::getPatientId, patientId);
        }
        return baseMapper.selectOne(lambdaQueryWrapper);
    }


    @Override
    public String getGroupName(Integer patientId) {
        String groupName = baseMapper.selectGroupNameByPatientId(patientId);
        return StrUtil.isBlank(groupName) ? Constant.NO_GROUP_NAME : groupName;
    }

    @Override
    public void removeGroupPatients(Integer groupId) {
        baseMapper.deleteGroupPatients(groupId);
    }

    @Override
    public void deleteRecordByPatientIds(Set<Integer> patientIds) {
        if (CollectionUtil.isNotEmpty(patientIds)) {
            baseMapper.deleteRecordByPatientIds(patientIds);
        }
    }
}
